import {Component} from '@angular/core';
import {NavController, NavParams} from 'ionic-angular';

import request from 'superagent';

import {HomePage1} from './home1';

@Component({
  templateUrl: 'build/pages/home/home.html'
})
export class HomePage {

  static get parameters() {
    return [[NavController], [NavParams]];
  }

  constructor(navCtrl, navParams) {
    this.navCtrl = navCtrl;
    this.navParams = navParams;

    this.start = 0;

    this.inTheaters = {};

    this._loadData()
      .then((result) => {
        this.inTheaters = result;
      });
  }

  doRefresh(refresher) {
    this.start = 0;
    this._loadData()
      .then((result) => {
        this.inTheaters = result;
      }).then(() => {
        refresher.complete();
      });
  }

  doInfinite(infiniteScroll) {
    this.start += 5;
    this._loadData()
      .then((result) => {
        result.subjects.forEach((subject) => {
          this.inTheaters.subjects.push(subject);
        });

        if (this.start > result.total) {
          this.start -= 5;
        }

        infiniteScroll.complete();
      });
  }

  _loadData() {
    return new Promise((resolve) => {
      request
        .get('http://10.3.1.2/v2/movie/in_theaters')
        .query({ start: this.start })
        .query({ count: 5 })
        .end((err, res) => {
          resolve(res.body);
        });
    });
  }

  toHome1() {
    console.log('toHome1');
    this.navCtrl.push(HomePage1, { aaa: 'hello.' });
  }
}
